from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .models import Users
import json

# 添加用户
@require_http_methods(["POST"])
def add_user(request):
    response = {}
    try:
        data = json.loads(request.body)
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')

        if not username or not email or not password:
            response['msg'] = '用户名、邮箱和密码不能为空'
            response['error_num'] = 1
            return JsonResponse(response)

        user = Users(username=username, email=email, password=password)
        user.save()
        response['msg'] = '用户添加成功'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 显示所有用户
@require_http_methods(["GET"])
def show_users(request):
    response = {}
    try:
        users = Users.objects.all().values('id', 'username', 'email', 'created_at')
        response['list'] = list(users)
        response['msg'] = '成功获取用户列表'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 修改用户
@require_http_methods(["PUT"])
def modify_user(request, user_id):
    response = {}
    try:
        user = Users.objects.get(id=user_id)
        data = json.loads(request.body)
        user.username = data.get('username', user.username)
        user.email = data.get('email', user.email)
        user.password = data.get('password', user.password)  # 可选择加密

        user.save()
        response['msg'] = '用户信息修改成功'
        response['error_num'] = 0
    except Users.DoesNotExist:
        response['msg'] = '用户不存在'
        response['error_num'] = 1
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


# 删除用户
@require_http_methods(["DELETE"])
def delete_user(request, user_id):
    response = {}
    try:
        user = Users.objects.get(id=user_id)
        user.delete()
        response['msg'] = '用户删除成功'
        response['error_num'] = 0
    except Users.DoesNotExist:
        response['msg'] = '用户不存在'
        response['error_num'] = 1
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

"""
代码说明
添加用户 (add_user)：接收 POST 请求，解析 JSON 数据并保存用户。密码会被自动加密。
显示用户 (show_users)：接收 GET 请求，返回所有用户的列表，包括用户名、邮箱和创建时间。
修改用户 (modify_users)：接收 PUT 请求，更新指定用户的信息。用户 ID 通过 JSON 数据传递。
删除用户 (delete_users)：接收 DELETE 请求，删除指定用户。用户 ID 同样通过 JSON 数据传递。


请求示例

添加用户：
curl -X POST http://127.0.0.1:8000/api/add_user/ 
-H "Content-Type: application/json" 
-d '{"username": "testuser", "email": "test@example.com", "password": "password123"}'


显示用户：
curl -X GET http://127.0.0.1:8000/api/show_users/


修改用户：
curl -X PUT http://127.0.0.1:8000/api/modify_user/ 
-H "Content-Type: application/json" 
-d '{"id": 1, "username": "newusername", "email": "newemail@example.com", "password": "newpassword123"}'


删除用户：
curl -X DELETE http://127.0.0.1:8000/api/delete_users/ 
-H "Content-Type: application/json" 
-d '{"id": 1}'


总结
确保在你的 Django 项目中正确配置了路由，然后测试这些 API 是否正常工作。如果有任何问题，请随时反馈。
"""